﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;
using System.Linq;
using System.Diagnostics;
using Pakxel.Framework;
using System.Xml.Linq;
using Pakxel.SmartLogistic.Admon;

namespace Pakxel.SmartLogistic
{
    public partial class WorkBench : Telerik.WinControls.UI.RadForm
    {
        IMenuManager MenuManager;
        IDatabaseConnection DatabaseConnection;
        public const string FILE_SETTINGS_NAME = "settings.xml";
        public static string iConnectionString;
        const string ROOT = "AppSettings";

        public WorkBench()
        {
            InitializeComponent();
        }

        public static string ConnectionString
        {
            get { return iConnectionString; }
        }

        private static System.Security.Principal.IPrincipal CurrentUser
        {
         get { return System.Threading.Thread.CurrentPrincipal; }
        }

        private void WorkBench_Load(object sender, EventArgs e)
        {
            try
            {
               MainApp.WriteToLog("App Starting...");
               this.DatabaseConnection = new DatabaseConnection(XElement.Load(System.Environment.CurrentDirectory + "\\" + FILE_SETTINGS_NAME));
               iConnectionString = this.DatabaseConnection.ConnectionString("PRODUCCION"); /// TODO : Modificar el proveedor de seguridad para que use el mismo ID
            }
            catch (SystemException se)
            {
                MainApp.WriteExceptionToLog(se);
                System.Environment.Exit(1);
            }

            //QueryViajesWorkBench queryViajes = new QueryViajesWorkBench() {MdiParent =this  };
            //queryViajes.Show();

            LoginForm loginForm = new LoginForm();
            loginForm.onUserAuthenticated += loginForm_onUserAuthenticated;
            loginForm.MdiParent = this;
            loginForm.Show();
        }

        void parametrosWorkBench_RecordSelected(object sender, Dummy e)
        {
           MainApp.WriteToLog(e.foo);  
        }

        void loginForm_onUserAuthenticated(object sender, EventArgs e)
        {
            MenuManager = new MenuManager(iConnectionString);

            RadMenuItem MI = new RadMenuItem();
            foreach (T001Menu M in MenuManager.GetMenuOptionFor(CurrentUser.Identity.Name))
            {
                MI = new RadMenuItem();
                MI.Name = M.T001Name;
                MI.Text = M.T001Text;
                MI.Visibility =  ElementVisibility.Visible;
                MI.Click += new EventHandler(Menu_Click);
                WorkBenchMenu.Items.Add(MI);
                RecursiveMenuLevel1(M.T001Name,M.T001ParentName);
            }
        }

        private void RecursiveMenuLevel1(string T001Name, string T001ParentName)
        {
            foreach (T001Menu SM in this.MenuManager.GetSubMenuOptionFor(CurrentUser.Identity.Name, T001Name))
            {
                    var OutputResult = from ResultSet in WorkBenchMenu.Items
                                       let ResultObject = ((string)ResultSet.Name)
                                       where ResultObject.Equals(SM.T001ParentName)
                                       select ResultSet;
                    if (OutputResult.Count() > 0)
                    {
                        IEnumerator<RadItem> enu = OutputResult.GetEnumerator();
                        enu.MoveNext();
                        RadMenuItem SubMenuItem = (RadMenuItem)enu.Current;
                        var MI = new RadMenuItem();
                        MI.Name = SM.T001Name;
                        MI.Text = SM.T001Text;
                        MI.Visibility = ElementVisibility.Visible;
                        MI.Click += new EventHandler(Menu_Click);
                        SubMenuItem.Items.Add(MI);
                        RecursiveMenuLevelN(SM.T001Name, SM.T001ParentName, SubMenuItem);
                    }
                    
            }
        }


        private void RecursiveMenuLevelN(string T001Name, string T001ParentName, RadMenuItem MenuObject)
        {
            foreach (T001Menu SM in this.MenuManager.GetSubMenuOptionFor(CurrentUser.Identity.Name, T001Name))
            {
                var OutputResult = from ResultSet in MenuObject.Items
                                   let ResultObject = ((string)ResultSet.Name)
                                   where ResultObject.Equals(SM.T001ParentName)
                                   select ResultSet;
                if (OutputResult.Count() > 0)
                {
                    IEnumerator<RadItem> enu = OutputResult.GetEnumerator();
                    enu.MoveNext();
                    RadMenuItem SubMenuItem = (RadMenuItem)enu.Current;
                    var MI = new RadMenuItem();
                    MI.Name = SM.T001Name;
                    MI.Text = SM.T001Text;
                    MI.Visibility = ElementVisibility.Visible;
                    MI.Click += new EventHandler(Menu_Click);
                    SubMenuItem.Items.Add(MI);
                    RecursiveMenuLevelN(SM.T001Name, SM.T001ParentName, SubMenuItem);
                }
            }
        }
        private void Menu_Click(object sender, EventArgs e)
        {
            try
            {
                var Mi = (RadMenuItem) sender; 
                Debug.Print("Name:"+Mi.Name); 
                switch(Mi.Name)
                {
                    case "MI001": // Catalogo de clientes
                        //Modulos.Clientes clientes = new Modulos.Clientes() { MdiParent = this };
                        //clientes.Show();
                      Modulos.CatEntity entities = new Modulos.CatEntity() { MdiParent = this };
                      entities.Show(); 
                        break;
                    case "MI002": // Catalogo de operadores
                        Modulos.Operadores operadores = new Modulos.Operadores() { MdiParent = this };
                        operadores.Show();
                        break;
                    case "MI003": // Catalogo de Lineas
                        Modulos.Transportistas transportista = new Modulos.Transportistas() { MdiParent = this };
                        transportista.Show();
                        break;
                    case "MI004": // Catalogo Destino/Origen
                        Modulos.Origen origen = new Modulos.Origen() { MdiParent = this };
                        origen.Show();
                        break;
                    case "MI005": // Catalogo de Remolques
                        Modulos.Remolques remolques = new Modulos.Remolques() { MdiParent = this };
                        remolques.Show();
                        break; 
                    case "MI006": // Catalogo de Unidades
                        Modulos.Unidades unidades = new Modulos.Unidades() { MdiParent = this };
                        unidades.Show();
                        break;
                    case "MI007": // Catalogo de Usuarios
                        break;
                    case "MI008": // Catalogo de Roles
                        break;
                    case "MI009": // Catalogo de Gastos
                        break;
                    case "MI010": // Parametros del Sistema
                        break;
                    case "MI011": // Asignacion de Viajes
                        ViajesWorkBench viajes = new ViajesWorkBench() { MdiParent =this };
                        viajes.Show();
                        break;
                    case "MI012": // Anticipos del Viaje
                        AnticiposWorkBench anticiposWorkBench = new AnticiposWorkBench() { MdiParent = this };
                        anticiposWorkBench.Show();
                        break;
                    case "MI013": // Carta Porte
                        CartaPorteWorkBench cartaporteWorkBench = new CartaPorteWorkBench() { MdiParent =this};
                        cartaporteWorkBench.Show();
                        break;
                    case "MI014": // Liquidacion
                        LiquidacionWorkBench liquidacionWorkBench = new LiquidacionWorkBench() { MdiParent = this };
                        liquidacionWorkBench.Show();
                        break;
                    case "MI015": // Factura
                        FacturaWorkBench facturasWorkBench = new FacturaWorkBench() { MdiParent =this};
                        facturasWorkBench.Show();
                        break;
                    case "MI016": // Vale de diesel
                        ValeDieselWorkBench valedieselWorkBench = new ValeDieselWorkBench() { MdiParent = this };
                        valedieselWorkBench.Show();
                        break;
                    case "MI017": // Query de Viajes
                        QueryViajesWorkBench queryViajes = new QueryViajesWorkBench() {MdiParent =this  };
                        queryViajes.Show();
                        break;
                    case "MI018": //Reporte de Cartas Porte
                        Pakxel.SmartLogistic.Reportes.CartasPorte CartasPorte = new Reportes.CartasPorte() { MdiParent = this };
                        CartasPorte.Show();
                        break;
                    case "MI019": // Cuentas x Cobrar
                        CxCWorkBench cxcWorkBench = new CxCWorkBench() { MdiParent = this };
                        cxcWorkBench.Show(); 
                        break;
                    case "MI020": // Cuentas x Pagar
                        CxPWorkBench cxpWorkBench = new CxPWorkBench() { MdiParent = this };
                        cxpWorkBench.Show(); 
                        break;
                    default:
                        break;
                }
            }
            catch (NullReferenceException ex)
            {
                MainApp.WriteToLog(ex.Message);
            }
        }

    }
}
